package exercise.channel.actualcombat.producerconsumer

import com.ww.exercise.channel.actualcombat.producerconsumer.ChannelProcessor
import com.ww.exercise.channel.actualcombat.producerconsumer.Config
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.time.Duration.Companion.seconds

fun main() = runBlocking {
    testFixedProcessor()
}

// 使用修复后的代码进行测试
suspend fun testFixedProcessor() {
    val processor = ChannelProcessor<String>(
        config = Config(
            channelCapacity = 100,
            consumerCount = 2,
            shutdownTimeout = 10.seconds
        )
    )

    // 启动慢消费者
    processor.startConsumers { item ->
        delay(100) // 每个项目处理100ms
        println("[消费了]: $item")
    }

    // 生产者
    val producerJob = GlobalScope.launch {
        for (i in 1..100) {
            val success = processor.produce("Item-$i")
            if (success) {
                println("===生产了数据Item-$i")
            } else {
                println("===生产失败Item-$i")
            }
            delay(10) // 生产速度快于消费
        }
        println("===生产者发送结束")
    }

    // 等待部分处理，然后关闭
    delay(2000)

    println("=== Initiating graceful shutdown ===")

    // 先打印详细状态
    val detailedStatus = processor.getDetailedStatus()
    println("Detailed status before shutdown: $detailedStatus")

    val result = processor.shutdown(timeout = 5.seconds)

    println(result.message)

    // 最终状态
    val finalMetrics = processor.getMetrics()
    val finalDetailed = processor.getDetailedStatus()

    println("=== Final Report ===")
    println("Metrics: $finalMetrics")
    println("Detailed: $finalDetailed")
//    println("Counters synchronized: ${finalMetrics.synchronizationError}")

    producerJob.join()
}